<template>
    <div class="edit-dialog-container">
        <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" destroy-on-close>
            <el-form ref="dialogFormRef" :model="state.content" :rules="formRules" size="default" label-width="90px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item prop="code" label="账户名称">
                            <el-input v-model="state.content.code" :disabled="state.dialog.type === 1" placeholder="请输入账户名称"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item prop="name" label="名称">
                            <el-input v-model="state.content.name" placeholder="请输入名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type === 0">
                        <el-form-item prop="newPassword" label="密码">
                            <el-input v-model="state.content.newPassword" placeholder="请输入密码" type="password"
                                autocomplete="new-password"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="菜单权限">
                            <el-tree :data="state.routerList" :props="{ label: 'name', children: 'children' }" show-checkbox
                                ref="elTreeRef" :highlight-current="true" @check="selectRouterCode" node-key="code"
                                :default-checked-keys="state.content.authMenuList" :expand-on-click-node="false"
                                :check-strictly="true" :default-expand-all="true">
                                <template #default="{ node, data }">
                                    <span class="custom-tree-node">
                                        <span>{{ t(data.meta.title) }}</span>
                                    </span>
                                    <el-button text type="primary" @click="settingHome(data)"
                                        v-show="data.component !== 'layout/routerView/parent'"
                                        :disabled="data.path === state.content.redirectURL || data.component === 'layout/routerView/parent'"
                                        :style="{ color: data.path === state.content.redirectURL && data.path !== '' ? 'red' : '#409eff' }">设为首页</el-button>
                                </template>
                            </el-tree>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="部门权限">
                                <el-tree :data="state.orgTreeData" :props="{ label: 'name', children: 'children' }"
                                    show-checkbox ref="perTreeRef" :highlight-current="true" @check="selectPerCode"
                                    node-key="code" :expand-on-click-node="false" check-strictly="true"
                                    :default-expand-all="true">
                                </el-tree>
                            </el-form-item>
                        </el-col> -->
                    <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="区域权限">
                            <el-tree :data="state.areaTree" :props="{ label: 'name', children: 'children' }" show-checkbox
                                ref="devTreeRef" :highlight-current="true" @check="selectOrgCode" node-key="code"
                                :expand-on-click-node="false" check-strictly="true" :default-expand-all="true"
                                :default-checked-keys="state.content.authAccessAreaCodes">
                            </el-tree>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onSubmitContinue" type="primary" size="default" v-if="state.dialog.type === 0">{{
                        t('message.btnName.continueSubmit')
                    }}</el-button>
                    <el-button @click="onSubmit" type="success" size="default">{{ t('message.btnName.submit')
                    }}</el-button>
                    <el-button @click="onCancel" size="default">{{ t('message.btnName.cancel') }}</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" >
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoutesList } from '/@/stores/routesList';
import { usePersonOrgTreeApi } from '/@/api/person/org';
import { useSystemAdminUpdateApi, useSystemAdminCreateApi, useSystemAdminQueryApi } from '/@/api/system/admin';
import { useAccessAreaTreeApi } from '/@/api/access/area';

// 定义子组件向父组件传值/事件
const { t } = useI18n();
const emit = defineEmits(['refresh']);

// 定义变量内容
const dialogFormRef = ref();
const elTreeRef = ref();

const useContent = () => {
    return {
        code: '', // 账户名称
        name: '', // 用户姓名
        remark: '', // 邮箱
        password: '', // 账户密码
        redirectURL: '/home',
        newPassword: '',
        authBtnList: [] as string[],
        authMenuList: [] as string[],
        dataScope: [] as string[],
        authAccessAreaCodes: [] as any[],
    }
}

const state = reactive({
    routerList: [] as any[],
    areaTree: [] as any[],
    checkAreaCode: [] as any[],
    dataScope: [],
    content: {} as any,
    dialog: {
        isShowDialog: false,
        type: 0,
        title: '',
    },
});

// 表单校验
const formRules = ref({
    code: [
        { required: true, message: '必填项不能为空', trigger: 'blur' },
        { min: 1, max: 40, message: '工号必须1-40位字母数字组合而成', trigger: 'blur' },
        // { pattern: /^[a-z1-9]/, message: '工号必须非0数字或小写字母开头', trigger: 'blur' },
    ],
    name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
    mobile: [{ pattern: /^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/, message: '请输入正确手机号', trigger: 'blur' },],
})

// 打开弹窗
const openDialog = async (code?: string) => {
    state.dialog.isShowDialog = true
    // 渲染部门树
    const { routesList } = useRoutesList()
    getDepData()
    getRegData()
    state.routerList = routesList
    if (code) {
        state.dialog.title = t('message.btnName.edit')
        state.dialog.type = 1
        queryItem(code)
    } else {
        state.dialog.title = t('message.btnName.addRow')
        state.dialog.type = 0
        state.content = useContent()
    }

};
// 设为首页
const settingHome = (data: any) => {
    ElMessageBox.confirm(
        `是否将 ${t(data.meta.title)} 设为首页？`,
        '提示',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    ).then(() => {
        state.content.redirectURL = data.path
        ElMessage({
            type: 'success',
            message: '设为首页成功，请保存配置',
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '操作取消',
        })
    })
}

// 选择路由
const selectRouterCode = (_checkedNodes: any, checkedKeys: { code: string, checkedNodes: any[], halfCheckedKeys: any[] }, _halfCheckedNodes: any, _halfCheckedKeys: any) => {
    let arrResult = [] as string[]
    checkedKeys?.checkedNodes?.forEach((element: { code: string; }) => {
        arrResult.push(element.code)
    });
    arrResult = arrResult.concat(checkedKeys.halfCheckedKeys)
    state.content.authMenuList = arrResult
}

// 获取部门权限
const getDepData = () => {
    useAccessAreaTreeApi('').then(({ content }) => {
        // console.log(content)
        state.areaTree = content
    })
}

// 勾选关联查询table
const selectOrgCode = (data: any) => {
    state.checkAreaCode.push(data)
    state.content.authAccessAreaCodes = state.checkAreaCode.map((item: any) => {
        return item.code
    })
}

// 获取区域权限
const getRegData = () => {
    usePersonOrgTreeApi().then(({ content }) => {
        console.log(content)
    })
}

// 关闭弹窗
const closeDialog = () => {
    state.dialog.isShowDialog = false;
    state.content = useContent()
    emit('refresh');
};
// 取消
const onCancel = () => {
    closeDialog();
};
const queryItem = (code: string) => {
    useSystemAdminQueryApi(code).then(({ content }) => {
        state.content = content
        state.content.authAccessAreaCodes = content.areaCodes
    })
}
// 提交
const onSubmit = () => {
    if (state.dialog.type === 1) {
        useSystemAdminUpdateApi(state.content).then(() => {
            closeDialog()
        })
    } else {
        useSystemAdminCreateApi(state.content).then(() => {
            closeDialog()
        })
    }
};
// 提交
const onSubmitContinue = () => {
    useSystemAdminCreateApi(state.content).then(() => {
        ElMessage({
            type: 'success',
            message: '新增成功'
        })
    }).then(() => {
        state.content = useContent()
    })
};

defineExpose({
    openDialog,
});
</script>


<style scoped lang="scss">
:deep(.el-dialog__header) {
    margin: 0;
    border-bottom: 1px dashed rgba(0, 0, 0, .2);
}

:deep(.el-dialog__footer) {
    border-top: 1px dashed rgba(0, 0, 0, .2);
}
</style>